<?php namespace app\api\controller;

use app\common\controller\AuthAndBind;
use think\Controller;
use think\Db;
use alisms\SendSms;
use esign\EsignHandle;

/**
 * api
 */
class TimedExecution extends Controller{
	
	public function __construct(){
		parent::__construct();
	}
	
	/**
	 * 执行分销返佣
	 */
	public function executeCommissionRebate(){
		$time = config("DELAY_REBATE_TIME");
		$date = date("Y-m-d H:i:s", time()-$time);
		
//		获取订单
		$where = [];
		$where[] = ['a.status', 'eq', 1];
		$where[] = ['a.is_delete', 'eq', 0];
		$where[] = ['a.check_date', 'elt', $date];
		$where[] = ['b.type', 'in', [1, 2]];
		$where[] = ['b.withdrawal_status', 'eq', '-1'];
		$order = Db::table("gd_order") -> alias('a') -> join('gd_reward b', 'a.id = b.order_id') -> field(['b.order_id']) -> where($where) -> group("b.order_id") -> select();
		
		Db::startTrans();
		if( !empty($order) ){
			foreach($order as $key => $val){
//				处理订单各级返佣
				$oldReward = Db::table("gd_reward") -> where(['order_id'=>$val['order_id'], 'withdrawal_status'=>'-1']) -> select();
				if( !empty($oldReward) ){
//					变更奖励为生效
					$res = Db::table("gd_reward") -> where(['order_id'=>$val['order_id'], 'withdrawal_status'=>'-1']) -> update(['withdrawal_status'=>'0']);
					if( !$res ){
						Db::rollback();
						returnResults2('-1', '变更奖励状态失败,请联系管理员');
					}
					
//					给用户账号加余额
					foreach ($oldReward as $k => $v) {
						if( $v['rewards'] > 0 ) {
							$re1 = Db::table("gd_user") -> where(['id'=>$v['referrer_id']]) -> setInc('rebate', $v['rewards']);
							$re2 = Db::table("gd_user") -> where(['id'=>$v['referrer_id']]) -> setInc('total_income', $v['rewards']);
							if( !$re1 || !$re2 ) {
								Db::rollback();
								returnResults2('-1', '变更用户信息失败,请联系管理员');
							}
						}
					}
				}
			}
		}
		Db::commit();
	}
	
	/**
	 * 执行分账
	 */
	public function wechatProfitsharing(){
		$date = date("Y-m-d H:i:s", strtotime(date("Y-m-d H:i:s", time())) - 60*10);
		$where[] = ['status', 'eq', 0];
		$where[] = ['date', 'gt', $date];
		$data = Db::table("gd_wechat_separate_fail") -> where($where) -> select();
		if( empty($data) ) return true;
		foreach ($data as $k => $v) {
			// 当前订单的付款数据
			$order = Db::table("gd_order") -> where(['id'=>$v['order_id']]) -> find();
			$shop = Db::table("gd_shop") -> where(['id'=>$order['shop_id']]) -> find();
			$orderPay = Db::table("gd_payment_records") -> where(['order_id'=>$order['id']]) -> find();
			$user = Db::table("gd_user") -> where(['id'=>$order['order_user_shop_parent_user_id']]) -> find();
			
			// 商店微信支付配置项
			$weChatConfig['MCH_ID'] = $shop['wechat_pay_mch_id'];
			$weChatConfig['SIGN_TYPE'] = 'MD5';
			$weChatConfig['API_V2'] = $shop['wechat_pay_api_v2'];
			
			// 分账信息
			$receivers = [
				[
					'type'=>'PERSONAL_OPENID',
					'account'=>$user['open_id'],
					'amount'=>$order['total_price'] * 100 * 0.1,
					'description'=>'用户消费',
				],
			];
			// 执行分账（当前订单）
			$re = controller("service/Wechat") -> profitsharing($weChatConfig, $orderPay['pay_code'], $receivers, $order['id']);
			if( $re['code'] == '1' ){
				$save['status'] = 1;
				$save['desc'] = 'SUCCESS';
			}else{
				$save['status'] = 2;
				$save['desc'] = $re['info']['err_code_des'];
			}
			$save['date'] = date("Y-m-d H:i:s", time());
			$data = Db::table("gd_wechat_separate_fail") -> where(['id'=>$v['id']]) -> update($save);
		}
	}
	
}

?>